package fr.afcepf.atod16.groupe1.projet2.configuration;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Serializable;
import java.net.MalformedURLException;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.Properties;
import javax.annotation.PostConstruct;
import javax.ejb.Singleton;
import javax.jws.WebService;

/**
 * EJB singleton permettant permettant de gérer l'url de rappel 
 * pour les mises à jour
 * @author cedric
 */
@Singleton
@WebService(endpointInterface="fr.afcepf.atod16.groupe1.projet2.configuration.ConfigurationRappelWebService", serviceName="ConfigurationRappel")
public class ConfigurationRappel implements ConfigurationRappelWebService, ConfigurationRappelLocal, Serializable {
    private URL urlEndpointToPush;
    
    /**
     * {@inheritDoc}
     */
    @Override
    public void addUrlEndpointToPush(URL url) {
        try {
            urlEndpointToPush = url;
            OutputStream fluxEcritureProperties;
            fluxEcritureProperties = new FileOutputStream(new File(Thread.currentThread().getContextClassLoader().getResource("url.properties").toURI()));
            
            Properties props = new Properties();
            props.setProperty("urlEndpointToPush", urlEndpointToPush.toString());
            props.store(fluxEcritureProperties, url.toString());
        } catch (IOException e) {
            e.printStackTrace();
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
    }
    
    /**
     * {@inheritDoc}
     */
    @Override
    public URL getUrlEndpointToPush() {
        return urlEndpointToPush;
    }

    /**
     * Charge l'url de rappel à partir du fichier properties lors du lancement
     * de l'application
     */
    @PostConstruct
    public void init() {
        try {
            InputStream fluxLectureProperties = Thread.currentThread().getContextClassLoader().getResourceAsStream("url.properties");
            Properties props = new Properties();
            props.load(fluxLectureProperties);

            urlEndpointToPush = new URL(props.getProperty("urlEndpointToPush"));
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    
}
